<template>
	<div>
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
			<el-form-item label="商品名称">
				<el-input v-model="formInline.name" placeholder="商品名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="quaryDevice()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<span class="demonstration">月{{formInline.value4}}</span>
				<el-date-picker
				  v-model="formInline.value4"
				  type="month"
				  :picker-options="pickerOptions0"
				  placeholder="选择查询月">
				</el-date-picker>
			  </el-form-item>
			 <el-form-item>
			  	<span class="demonstration">月</span>
			  	<el-date-picker
			  	  v-model="formInline.value2"
			  	  type="month"
				  :picker-options="pickerOptions1"
			  	  placeholder="选择结束月">
			  	</el-date-picker>
			  </el-form-item>
		</el-form>
		<div class="panel">
			<el-button @click.stop="getDevice" size="small">
				<i class="el-icon-refresh"></i>
			</el-button>
			<el-button type="primary" @click="dialogVisible = true" icon="plus" size="small">新增</el-button>
			<el-button type="danger" @click="deleteMore(multipleSelection)" icon="plus" size="small">批量删除</el-button>
		</div>
		<el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange"
		 v-loading="tableLoading">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column prop="name" label="设备名称">
			</el-table-column>
			<el-table-column prop="desc" label="设备描述" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="deviceFrom" label="设备来源">
			</el-table-column>
			<el-table-column prop="buyer" label="采购人员">
			</el-table-column>
			<el-table-column prop="deviceID" label="设备ID">
			</el-table-column>
			<el-table-column prop="status" label="是否启用" :filters="[{ text: '禁用', value: false }, { text: '启用', value: true }]"
			 :filter-method="filterTag" filter-placement="bottom-end">
				<template slot-scope="scope">
					<el-tag :type="scope.row.status === true ? 'success' : 'danger'" disable-transitions>{{scope.row.status === true ? '启用':'禁用'}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" >
				<template slot-scope="scope">
					 {{scope.row.createTime|timeForm}}
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="更新时间">
				<template slot-scope="scope">
					 {{scope.row.updateTime|timeForm}}
				</template>
			</el-table-column>
			<!-- <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormat">
			</el-table-column> -->
			<el-table-column label="操作" fixed="right" width="200">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" class="fl">批量删除</el-button> -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="page.skipPage"
			 :page-sizes="[5,10,15]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
			 class="fr">
			</el-pagination>
		</el-col>
		<el-upload
		    class="avatar-uploader"
		    action="/api/imgList/createImg"
		    :on-success="uploadSuccess"
		    :on-error="uploadError"
			:on-change="handleFileUploaderChange"
		    :before-upload="beforeUpload">
		</el-upload>
		<el-dialog title="新增设备" :visible.sync="dialogVisible" width="70%">
			<el-form :model="device" :rules="rules" status-icon ref="device" label-width="80px">
				<el-form-item label="名称" :label-width="formLabelWidth" prop="name">
					<el-input v-model="device.name"></el-input>
				</el-form-item>
				<el-form-item label="描述" :label-width="formLabelWidth">
					<el-input v-model="device.desc"></el-input>
				</el-form-item>
				<el-form-item label="设备来源" :label-width="formLabelWidth">
					<el-input v-model="device.deviceFrom"></el-input>
				</el-form-item>
				<el-form-item label="采购人员" :label-width="formLabelWidth">
					<el-input v-model="device.buyer"></el-input>
				</el-form-item>
				<el-form-item label="设备详情" :label-width="formLabelWidth">
					<quill-editor v-model.trim="device.content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
						@change="onEditorChange($event)">
					</quill-editor>
				</el-form-item>
				<el-form-item label="设备ID" :label-width="formLabelWidth" prop="deviceID">
					<el-input v-model="device.deviceID"></el-input>
				</el-form-item>
				<el-form-item label="是否启用">
					<el-switch v-model="device.status"></el-switch>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click.native="createDevice" :loading="addLoading">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 编辑设备 -->
		<el-dialog title="编辑设备" :visible.sync="editDialogVisible" width="70%">
			<el-form :model="editDevice" :rules="rules" status-icon ref="editDevice" label-width="80px">
				<el-form-item label="名称" :label-width="formLabelWidth" prop="name">
					<el-input v-model="editDevice.name"></el-input>
				</el-form-item>
				<el-form-item label="描述" :label-width="formLabelWidth">
					<el-input v-model="editDevice.desc"></el-input>
				</el-form-item>
				<el-form-item label="设备来源" :label-width="formLabelWidth">
					<el-input v-model="editDevice.deviceFrom"></el-input>
				</el-form-item>
				<el-form-item label="采购人员" :label-width="formLabelWidth">
					<el-input v-model="editDevice.buyer"></el-input>
				</el-form-item>
				<el-form-item label="设备详情" :label-width="formLabelWidth">
					<!-- <quill-editor v-model.trim="editDevice.content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
						@change="onEditorChange($event)">
					</quill-editor> -->
				</el-form-item>
				<el-form-item label="设备ID" :label-width="formLabelWidth" prop="deviceID">
					<el-input v-model="device.deviceID"></el-input>
				</el-form-item>
				<el-form-item label="是否启用">
					<el-switch v-model="editDevice.status"></el-switch>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click.native="updateDevice" :loading="addLoading">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import { formatDate } from '../../until/until'
	export default {
		data() {
			var container =[
				  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
				  ['blockquote', 'code-block'],
			
				  [{'header': 1}, {'header': 2}],               // custom button values
				  [{'list': 'ordered'}, {'list': 'bullet'}],
				  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
				  [{'direction': 'rtl'}],                         // text direction
			
				  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
				  [{'header': [1, 2, 3, 4, 5, 6, false]}],
			
				  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
				  [{'font': []}],
				  [{'align': []}],
				  ['link', 'image'],
				  ['clean']                                         // remove formatting button
			  ]
			return {
				pickerOptions0: {
					disabledDate: (time) => {
						return time.getTime() > Date.now();
					}
				},
				pickerOptions1: {
					disabledDate: (time) => {
						console.log(time.getTime() < this.formInline.value4)
						return time.getTime() < this.formInline.value4 || time.getTime() > Date.now();
					}
				},
				dialogVisible: false,
				formInline: {
					"name":'',
					"status": '',
					"value4":'',
					"value2":'',
				},
				imgBase64Array:[],
				imgSrc: '',
				addLoading: false,
				tableLoading: false,
				quillUpdateImg : false,
				formLabelWidth: '120px',
				editDialogVisible: false,
				page: {
					pageSize: 10,
					skipPage: 1,
				},
				editorOption: {
					modules:{
						
						toolbar: {
							container: container,
							handlers: {
								'image': function(value){
									console.log(value)
									let params = {
										imgUrl: this.imgSrc
									}
									if(value){
										console.log(this.imgSrc)
										document.querySelector('.avatar-uploader input').click()
										// document.querySelector('.avatar-uploader input').click(function(){
										// 	this.$ajax.post('/api/imgList/createImg',params).then((res) => {
										// 		console.log(res)
										// 	})
										// })
									}else{
										this.quill.format('image',false)
									}
								}
							}
							
						}
					}
				},
				total: 10,
				device: {
					name: '',
					createTime: '',
					updateTime: '',
					status: false,
					desc: '',
					deviceFrom: '',
					buyer: '',
					content:'',
					deviceID: '',
				},
				editDevice: {
					name: '',
					createTime: '',
					updateTime: '',
					status: false,
					desc: '',
					content:'',
					deviceFrom: '',
					buyer: '',
					deviceID: '',
				},
				rules: {
					name: [{
						required: true,
						message: '请输入设备名',
						trigger: 'blur'
					}],
					deviceID: [{
						required: true,
						message: '请输入设备ID',
						trigger: 'blur'
					}]

				},
				edit: {
					name: [{
						required: true,
						message: '请输入设备名',
						trigger: 'blur'
					}],
					deviceID: [{
						required: true,
						message: '请输入设备ID',
						trigger: 'blur'
					}]

				},
				tableData: [],
				multipleSelection: [],
				ids: []
			}
		},
		filters:{
			timeForm: function(value){
				return formatDate(value);
			}
		},
		computed: {
			editor() {
				return this.$refs.myQuillEditor.quill;
			},
		},
		methods: {
			// toggleSelection(rows) {
			// 	if (rows) {
			// 		rows.forEach(row => {
			// 			this.$refs.multipleTable.toggleRowSelection(row);
			// 		});
			// 	} else {
			// 		this.$refs.multipleTable.clearSelection();
			// 	}
			// },
			handleSelectionChange(val) {
				this.multipleSelection = val;
				console.log(val)
			},
			//新增设备
			createDevice() {
				this.$refs.device.validate((valid) => {
					if (valid) {
						this.logining = true
						var date = new Date();
						this.device.createTime = date;
						this.device.updateTime = date;
						this.$ajax.post('/api/device/createDevice', this.device).then((res) => {
							console.log(res)
							this.logining = false
							if (res.data.code == 1) {
								this.dialogVisible = false
								this.$message({
									message: res.data.msg,
									type: 'success'
								});
								this.getDevice()
							} else {
								this.$message.error(res.data.msg);
							}
						})
					}
				})
			},
			updateDevice() {
				this.$refs.editDevice.validate((valid) => {
					if (valid) {
						this.logining = true
						var date = new Date();
						var year = date.getFullYear();
						var month = date.getMonth() + 1;
						var strDate = date.getDate();
						if (month >= 1 && month <= 9) {
							month = "0" + month;
						}
						if (strDate >= 0 && strDate <= 9) {
							strDate = "0" + strDate;
						}
						var currentdate = year + '-' + month + '-' + strDate;
						this.editDevice.updateTime = currentdate;
						this.$ajax.post('/api/device/updateDevice', this.editDevice).then((res) => {
							console.log(res)
							this.logining = false
							this.editDialogVisible = false;
							if (res.data.code == 1) {
								this.$message({
									message: res.data.msg,
									type: 'success'
								});
								this.getDevice()

							} else {
								this.$message.error(res.data.msg);
							}
						})
					}
				})
			},
			//获取分页列表
			getDevice() {
				this.tableLoading = true
				this.$ajax.post('/api/device/getDevicePage?pageSize=' + this.page.pageSize + '&skipPage=' + this.page.skipPage,
					this.page).then((res) => {
					console.log(res)
					this.tableLoading = false
					this.tableData = res.data.data
					// this.total = res.data.total
					// dateFormat(this.tableData.updateTime)
				})
				this.$ajax.post('/api/device/getDevice').then((res) => {
					this.total = res.data.length
				})
			},
			filterTag(value, row) {
				console.log(row.status)
				return row.status == value
			},
			//每次点击更改条数值
			handleSizeChange(val) {
				console.log(val);

				this.page.pageSize = val;
				this.getDevice()
			},
			//每次点击更改页码值
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.page.skipPage = val;
				this.getDevice()
			},
			handleEdit(index, row) {
				console.log(index);
				this.editDialogVisible = true;
				this.editDevice = Object.assign({}, row);
			},
			handleDelete(index, row) {
				console.log(index, row);
				this.$ajax.post('/api/device/deleteDevice', {
					"_id": row._id
				}).then((res) => {
					console.log(res)
					if (res.data.code == -1) {
						this.$message({
							message: res.data.msg,
							type: 'success'
						});
						this.getDevice()
					} else {
						this.$message.error(res.data.msg);
					}
				})
			},
			//删除多个
			deleteMore(row) {
				this.$confirm('此操作将永久删除选中信息, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					row.forEach(element => {
						this.ids.push(element._id)
						console.log(this.ids)
					})
					this.$ajax.post('/api/device/deleteDeviceMore', this.ids).then((res) => {
						if (res.data.code == -1) {
							this.$message({
								message: res.data.msg,
								type: 'success'
							});
							this.getDevice()
						} else {
							this.$message.error(res.data.msg);
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//查询
			quaryDevice() {
				this.tableLoading = true
				this.$ajax.post('/api/device/findByName',{"name":this.formInline.name}).then((res) => {
					console.log(res.data)
					this.tableLoading = false
					this.tableData = res.data
				})
			},
			
			beforeUpload(file,fileList) {
				// 显示loading动画
				this.quillUpdateImg = true
			},
			uploadSuccess(response, file, fileList){
				// 获取富文本组件实例
				let quill = this.$refs.myQuillEditor.quill
				 // 如果上传成功
				if (response.code == 1) {
					
					// 获取光标所在位置
					let length = quill.getSelection().index;
					// 插入图片  res.info为服务器返回的图片地址
					quill.insertEmbed(length, 'image', response.data.url)
					// 调整光标到最后
					quill.setSelection(length + 1)
				} else {
					this.$message.error('图片插入失败')
				}
				// loading动画消失
				this.quillUpdateImg = false
			},
			uploadError() {
				// loading动画消失
				this.quillUpdateImg = false
				this.$message.error('图片上传失败')
			},
			handleFileUploaderChange(file,fileList){
				console.log(file)
				console.log(fileList)
				const isLt2M = file.size / 1024 / 1024 < 2;
				if(!isLt2M){
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}else{
					let reader = new FileReader()
					reader.readAsDataURL(file.raw)
					reader.onload = function(event){
						this.imgSrc = event.target.result
					}
				}
			
			},
			
			onEditorReady(editor) { // 准备编辑器
			},
			onEditorBlur() {}, // 失去焦点事件
			onEditorFocus() {}, // 获得焦点事件
			onEditorChange() {}, // 内容改变事件
		},
		created() {
			this.getDevice()
		},
		
	}
</script>

<style scoped>
	.panel {
		margin-bottom: 20px;
	}
</style>
